<template>
  <div class="container">
    <!-- 顶部栏 -->
    <div class="headerBox">
      <myNav></myNav>
    </div>
    <!-- logo区域 -->
    <myLogoArea></myLogoArea>
    <!-- 购物车区域 -->
    <div class="cart-container">
      <!-- 顶部标题 -->
      <div class="cart-header">
        <h2>Cart({{ items.length }})</h2>
      </div>

      <!-- 商品表格 -->
      <div class="cart-table">
        <!-- 表头 -->
        <div class="table-header">
          <div class="cell check-cell">
            <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" :true-value="1" :false-value="0" />
            <span>选择全部</span>
          </div>
          <div class="cell name-cell">商品名称</div>
          <div class="cell note-cell">备注</div>
          <div class="cell price-cell">单价</div>
          <div class="cell quantity-cell">数量</div>
          <div class="cell amount-cell">金额</div>
          <div class="cell action-cell">编辑</div>
        </div>

        <!-- 商品列表 -->
        <div class="product-list">
          <div v-for="(item, index) in items" :key="index" class="product-item">
            <div class="cell check-cell">
              <input type="checkbox" @change="updateSelectAll(item)" v-model="item.isSelect" :true-value="1"
                :false-value="0" />
            </div>

            <div class="cell name-cell">
              <div class="product-info-wrapper">
                <img :src="item.imageUrl" class="product-image" />
                <div class="product-info">
                  <div class="product-title">{{ item.title }}</div>
                  <div class="product-spec">{{ item.spec }}</div>
                  <div class="product-spec_detail">{{ item.color }}</div>
                  <div class="product-spec_detail">{{ item.size }}</div>
                </div>
              </div>
            </div>

            <div class="cell note-cell">
              {{ item.remark || '无备注' }}
            </div>

            <div class="cell price-cell">{{ item.price | currency }}</div>

            <div class="cell quantity-cell">
              <!-- <button @click="decrement(index)" :disabled="item.quantity <= 1">-</button>
              <input type="number" v-model.number="item.quantity" min="1" @change="validateQuantity(index)"
                style="-webkit-appearance: none; -moz-appearance: textfield; appearance: none;" />
              <button @click="increment(index)">+</button> -->

              <el-input-number v-model="item.quantity" @change="prodectNumberCalculate(index)" :min="1" label="描述文字"></el-input-number>
            </div>

            <div class="cell amount-cell">{{ item.price * item.quantity | currency }}</div>

            <div class="cell action-cell">
              <button class="delete-btn" @click="removeItem(index)">删除</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部结算 -->
      <div class="checkout-footer">
        <div class="footer-left">
          <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" :true-value="1" :false-value="0" />
          <span>选择全部</span>
          <button class="delete-btn" @click="removeSelectedItems" :disabled="selectedCount === 0">
            删除选中的商品
          </button>
        </div>

        <div class="total-info">
          <div class="total-item">
            <span>{{ selectedCount }} 件</span>
            <span class="total-price">合计（不包含国际运费）</span>
          </div>

          <div class="price-display">
            <div class="cny-price">CN￥{{ totalPrice }}</div>
            <div class="usd-price">US${{ totalPriceUsd }}</div>
          </div>
          <button class="submit-btn" :disabled="selectedCount === 0" @click="submitResult">结算</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import myLogoArea from '@/components/myHome/myLogoArea'
import myNav from '@/components/myHome/myNav'
import { getCarList, setCarSingleSelect, setCarAllSelect, delCar, setCarNum } from "@/api/myBuyCar/index"

export default {
  name: "mybuyCar",
  components: {
    myLogoArea,
    myNav,
  },
  data() {
    return {
      items: [],
      selectAll: 0,
      is_select: 0,
      num: 1
    }
  },


  computed: {
    selectedCount() {
      return this.items.filter(item => item.isSelect).length
    },
    totalPrice() {
      const total = this.items.reduce((sum, item) => {
        return item.isSelect ? sum + item.price * item.quantity : sum
      }, 0)
      return isNaN(total) ? '0.00' : total.toFixed(2)
    },
    totalPriceUsd() {
      const price = parseFloat(this.totalPrice)
      return isNaN(price) ? '0.00' : (price / 7.15).toFixed(2)
    }
  },
  filters: {
    currency(value) {
      if (value === undefined || value === null || isNaN(value)) {
        return 'CN ¥0.00'
      }
      return `CN ¥${Number(value).toFixed(2)}`
    }
  },
  created() {
    this.fetchCartData()
  },
  methods: {
    // 提交结果
    submitResult() {
      this.$router.push("/myOrderShow")
    },
    fetchCartData() {
      getCarList().then(res => {
        // 确保每个商品都有checked属性
        this.items = res.rows.map(item => ({
          ...item,
        }))

        console.log(this.items);
        this.setAllSelect();


        // 设置全选


      }).catch(error => {
        console.error('获取购物车数据失败:', error)
        // 使用默认数据作为后备
        this.items = [
          {
            imageUrl: require('@/assets/imgs/4.png'),
            title: 'Oshea stars with beaded gold dress...',
            spec: 'Size:1/S; Color Classification:Black',
            price: 790,
            quantity: 2,
            checked: false,
            remark: ''
          },
          {
            imageUrl: require('@/assets/imgs/6.png'),
            title: 'Oshea stars with beaded gold dress...',
            spec: 'Size:1/S; Color Classification:Black',
            price: 790,
            quantity: 2,
            checked: false,
            remark: ''
          },
          {
            imageUrl: require('@/assets/imgs/5.png'),
            title: 'Oshea stars with beaded gold dress...',
            spec: 'Size:1/S; Color Classification:Black',
            price: 790,
            quantity: 2,
            checked: false,
            remark: ''
          },
        ]
      })
    },
    prodectNumberCalculate(index) {
      let id = this.items[index].id + '';
      let num = this.items[index].quantity + '';
      setCarNum({cartId: id, quantity: num}).then(res => {

      }).catch(error => { 

      })
    },
    toggleSelectAll() {
      // this.items.forEach(item => {
      //   item.checked = this.selectAll
      // })
      // // 0 不全选 1 全选
      // if (this.is_select == 1) {
      //   this.is_select = 0
      // } else if (this.is_select == 0) {
      //   this.is_select = 1
      // }

      // // 让单选框都选中
      // this.items.forEach((res, index) => {
      //   this.$set(this.items, index, {
      //     ...res, // 保留其他属性
      //     isSelect: this.is_select == 1 ? 1 : 0 // 动态赋值
      //   });
      // });

      // // 调用全选的接口 持久化保存这个状态
      setCarAllSelect(this.selectAll).then(res => {
        this.fetchCartData()
      })

    },
    updateSelectAll(item) {
      // this.selectAll = this.items.every(item => item.checked)

      // 是否需要勾选全选
      this.setAllSelect();



      // 单选按钮持久化
      setCarSingleSelect({ is_select: item.isSelect, cartItemId: item.id }).then(res => {

      }).catch(error => {

      })


    },
    setAllSelect() {
      let num = 0;
      this.items.forEach(res => {
        if (res.isSelect == 1) {
          num++;
        }
      })
      if (num == this.items.length && this.items.length !== 0) {
        this.selectAll = 1
      } else {
        this.selectAll = 0
      }
    },
    increment(index) {
      this.items[index].quantity++
    },
    decrement(index) {
      if (this.items[index].quantity > 1) {
        this.items[index].quantity--
      }
    },
    validateQuantity(index) {
      if (this.items[index].quantity < 1 || isNaN(this.items[index].quantity)) {
        this.items[index].quantity = 1
      }
    },
    // 删除单个
    removeItem(index) {
      // this.items.splice(index, 1)
      // this.updateSelectAll()
      // let ids = [];

      // // 思路，每个item项里面都有一个isSelect，是否被选中，要是选中了，我们就可以记录
      // this.items.forEach((res, index) => {
      //   // 代表被选中
      //   if (res.isSelect == 1) {

      //     // 拿到他的id
      //     ids.push(res.id);
      //   }
      // })

      // // 把数组[] 变成字符串形式
      // const strIds = ids.join(',')

      delCar(this.items[index].id).then(res => {
        this.fetchCartData()
      }).catch(error => {

      })
    },
    // 删除选中的商品
    removeSelectedItems() {
      // 思路：把items里面的id为1都记录一下
      let ids = [];
      this.items.forEach((res, index) => {
        // 代表被选中
        if (res.isSelect == 1) {

          // 拿到他的id
          ids.push(res.id);
        }
      })

      // 把数组[] 变成字符串形式
      const strIds = ids.join(',')
      delCar(strIds).then(res => {
        this.fetchCartData()
      }).catch(error => {

      })
    }
  }
}
</script>
<style lang="scss" scoped>
.cart-container {
  max-width: 90%;
  margin: 10px auto;
  padding: 20px;
  background: white;
  font-family: Arial, sans-serif;

  .cart-header {
    padding: 20px 0;
    border-bottom: 1px solid #eee;

    h2 {
      margin: 0;
      font-size: 24px;
    }
  }

  .cart-table {

    .table-header,
    .product-item {
      display: flex;
      align-items: center;
      padding: 15px 0;
      border-bottom: 1px solid #eee;

      .cell {
        padding: 0 10px;
        box-sizing: border-box;

        &.check-cell {
          width: 10%;
          min-width: 100px;
          display: flex;
          align-items: center;

          input {
            margin-right: 8px;
          }
        }

        &.name-cell {
          width: 25%;
        }

        &.note-cell {
          width: 15%;
        }

        &.price-cell {
          width: 10%;
          text-align: center;
        }

        &.quantity-cell {
          width: 15%;
          text-align: center;
        }

        &.amount-cell {
          width: 10%;
          text-align: center;
        }

        &.action-cell {
          width: 10%;
          text-align: center;
        }
      }
    }

    .product-item {
      .name-cell {
        .product-info-wrapper {
          display: flex;
          align-items: center;

          .product-image {
            width: 80px;
            height: 100px;
            margin-right: 15px;
            object-fit: cover;
          }

          .product-info {
            .product-title {
              font-size: 14px;
              margin-bottom: 5px;
            }

            .product-spec {
              color: #666;
              font-size: 12px;
            }

            .product-spec_detail {
              color: #969696;
              font-size: 11px;
            }
          }
        }
      }

      .quantity-cell {
        display: flex;
        justify-content: center;
        align-items: center;

        button {
          padding: 5px 10px;
          border: 1px solid #ddd;
          background: white;
          cursor: pointer;

          &:hover {
            background: #f5f5f5;
          }
        }

        input {
          width: 50px;
          padding: 5px;
          text-align: center;
          border: 1px solid #ddd;
          margin: 0 5px;
        }
      }
    }
  }

  .checkout-footer {
    display: flex;
    justify-content: space-between;
    padding: 20px 0;
    margin-top: 30px;
    align-items: center;

    .footer-left {
      display: flex;
      align-items: center;
      gap: 15px;
    }

    .total-info {
      text-align: right;

      .total-item {
        margin-bottom: 10px;

        .total-price {
          margin-left: 20px;
          color: #666;
        }
      }

      .price-display {
        margin: 10px 0;

        .cny-price {
          font-size: 24px;
          color: #e4393c;
        }

        .usd-price {
          color: #666;
          font-size: 14px;
        }
      }
    }
  }

  .delete-btn {
    color: #e4393c;
    border: 1px solid #e4393c;
    background: white;
    padding: 5px 15px;
    border-radius: 3px;
    cursor: pointer;

    &:hover {
      background: #ffeceb;
    }
  }

  .submit-btn {
    background: #e4393c;
    color: white;
    border: none;
    padding: 12px 40px;
    border-radius: 3px;
    cursor: pointer;
    font-size: 16px;

    &:hover {
      background: #c03537;
    }
  }
}
</style>